const path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");

module.exports = {
    // mode: "development",
    // 生产环境下会自动压缩js代码
    mode: "production",
    entry: {
        index: './src/index.js'
    },
    output: {
        filename: '[name]-[contenthash].js',
        path: path.resolve(__dirname, 'dist')
    },
    devServer: {
        contentBase: path.join(__dirname, "dist"),
        compress: true,
        hot: true,
        port: 3000
    },
    resolve: {
        extensions: [".js", ".json", ".jsx"],
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env', '@babel/preset-react'],
                        cacheDirectory: true
                    }
                },
                exclude: /(node_modules|bower_components)/,
            }, {
                test: /\.(jpg|png|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        name: '[name]_[hash].[ext]',
                        outputPath: 'images/',
                        limit: 10240
                    }
                }
            }, {
                test: /\.(eot|ttf|svg)$/,
                use: {
                    loader: 'file-loader'
                }
            }, {
                test: /\.less$/,
                use: [
                    //添加loader,将css打成单独的文件,用于生产模式，替换 style-loader 
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            
                        }
                    },
                    "css-loader",
                    'less-loader'
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'src/html/index.html'
        }),
        new CleanWebpackPlugin(),
        // 将css打成单独的文件
        new MiniCssExtractPlugin({
            filename: "[name]-[contenthash].css",
            chunkFilename: "[id].css"
        }),

        // optimize-css-assets-webpack-plugin 压缩 CSS
        new OptimizeCSSAssetsPlugin({})
    ],

}